package com.dave.weixin.common.nio.channel;

import sun.rmi.runtime.Log;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.channels.FileChannel;

/**
 * Created by Dave on 2018/7/10
 * Describes 通道之间的数据传输
 */
public class TransferData {

    ///////////////////////////////////////////////////////////////////////////
    // FileChannel的 transferFrom可以以将数据从源通道传输到FileChannel
    //如果源通道的剩余空间小于 count 个字节，则所传输的字节数要小于请求的字节数。
    ///////////////////////////////////////////////////////////////////////////


    public static void main(String[] args) throws IOException {
        //源通道
        RandomAccessFile fromFile = new RandomAccessFile("", "rw");
        FileChannel fromChannel = fromFile.getChannel();

        //目标通道
        RandomAccessFile toFile = new RandomAccessFile("", "rw");
        FileChannel toChannel = toFile.getChannel();

        //position:从何处开始像target写入
        long position = 0;
        //count:至多传输多少个字节
        long count = fromChannel.size();

        //从源通道传输到FileChannel from----->to
        toChannel.transferFrom(fromChannel, position, count);

        //将数据从FileChannel传输到其他的channel中  from----to
        fromChannel.transferTo(position, count, toChannel);


    }
}
